package com.example.mydy;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mydy.adapter.TaskAdapter;
import com.example.mydy.api.ApiClient;
import com.example.mydy.api.UserApi;
import com.example.mydy.model.CommonResponse;
import com.example.mydy.model.InviterResponse;
import com.example.mydy.model.Task;
import com.example.mydy.model.TaskListResponse;
import com.example.mydy.utils.ImageUtils;
import com.example.mydy.utils.NetworkUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Locale;
import java.util.Date;
import java.text.SimpleDateFormat;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class TaskManagementActivity extends AppCompatActivity implements TaskAdapter.TaskListener {
    private static final String TAG = "TaskManagementActivity";
    private static final String PREFS_NAME = "MyAppPrefs";
    private static final String KEY_TOKEN = "token";

    private Toolbar toolbar;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private ProgressBar progressBar;
    private TextView tvNoTasks;
    private FloatingActionButton fabAddTask;
    
    private List<Task> tasks = new ArrayList<>();
    private TaskAdapter adapter;
    private UserApi userApi;

    // 声明广播接收器
    private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("task_update")) {
                // 收到任务更新的广播，刷新任务列表
                loadTasks();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_management);
        
        initViews();
        initUserApi();
        setupRecyclerView();
        loadTasks();

        // 注册广播接收器
        LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, new IntentFilter("task_update"));
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播接收器
        LocalBroadcastManager.getInstance(this).unregisterReceiver(messageReceiver);
    }
    
    private void initViews() {
        // 初始化顶部工具栏
        toolbar = findViewById(R.id.toolbar_task_management);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
        
        // 返回按钮
        findViewById(R.id.btn_back).setOnClickListener(v -> finish());
        
        // 其他视图组件
        recyclerView = findViewById(R.id.rv_tasks);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
        progressBar = findViewById(R.id.progress_bar);
        tvNoTasks = findViewById(R.id.tv_no_tasks);
        // fabAddTask = findViewById(R.id.fab_add_task); // 如果找不到此ID，注释掉
        
        // 设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener(this::loadTasks);
        
        /*
        // 添加任务按钮
        fabAddTask.setOnClickListener(v -> {
            Toast.makeText(this, "添加新任务", Toast.LENGTH_SHORT).show();
        });
        */
    }
    
    private void initUserApi() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiClient.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        userApi = retrofit.create(UserApi.class);
    }
    
    private void setupRecyclerView() {
        // 初始化adapter和RecyclerView
        adapter = new TaskAdapter(tasks, this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }
    
    private void loadTasks() {
        progressBar.setVisibility(View.VISIBLE);
        
        String token = NetworkUtils.getAuthToken(this);
        if (token == null || token.isEmpty()) {
            Toast.makeText(this, "未登录，请先登录", Toast.LENGTH_SHORT).show();
            loadFallbackData();
            return;
        }
        
        UserApi api = NetworkUtils.getAuthenticatedUserApi(this);
        Call<TaskListResponse> call = api.getTasks("Bearer " + token);
        call.enqueue(new Callback<TaskListResponse>() {
            @Override
            public void onResponse(Call<TaskListResponse> call, Response<TaskListResponse> response) {
                progressBar.setVisibility(View.GONE);
                
                if (response.isSuccessful() && response.body() != null) {
                    TaskListResponse taskResponse = response.body();
                    if (taskResponse.isSuccess()) {
                        tasks.clear();
                        tasks.addAll(taskResponse.getTasks());
                        adapter.notifyDataSetChanged();
                        updateTaskCountText();
                    } else {
                        Toast.makeText(TaskManagementActivity.this, 
                                       "加载失败: " + taskResponse.getMessage(), 
                                       Toast.LENGTH_SHORT).show();
                        loadFallbackData();
                    }
                } else {
                    Toast.makeText(TaskManagementActivity.this, 
                                   "加载失败: " + response.code(), 
                                   Toast.LENGTH_SHORT).show();
                    loadFallbackData();
                }
            }
            
            @Override
            public void onFailure(Call<TaskListResponse> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(TaskManagementActivity.this, 
                               "网络错误: " + t.getMessage(), 
                               Toast.LENGTH_SHORT).show();
                loadFallbackData();
            }
        });
    }

    private void loadFallbackData() {
        progressBar.setVisibility(View.GONE);
        tvNoTasks.setVisibility(View.VISIBLE);
        
        // 清空任务列表
        tasks.clear();
        adapter.notifyDataSetChanged();
        
        // 向用户显示错误提示
        Toast.makeText(this, "无法从服务器加载任务数据，请检查网络连接", Toast.LENGTH_LONG).show();
        
        // 记录日志
        Log.e(TAG, "从服务器获取任务数据失败，无法显示任务列表");
    }

    private void updateTaskCountText() {
        // 实现更新任务数量文本的逻辑
    }

    @Override
    public void onTaskSelected(Task task) {
        showTaskDetailDialog(task);
    }

    private void showTaskDetailDialog(Task task) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_admin_task_detail, null);
        builder.setView(view);
        
        TextView tvTaskTitle = view.findViewById(R.id.tv_task_title);
        TextView tvTaskDesc = view.findViewById(R.id.tv_task_description);
        TextView tvTaskSubmitter = view.findViewById(R.id.tv_task_submitter);
        ImageView ivTaskImage = view.findViewById(R.id.iv_task_image);
        Button btnApprove = view.findViewById(R.id.btn_approve);
        Button btnReject = view.findViewById(R.id.btn_reject);
        
        // 获取奖励信息TextView(如果存在)
        TextView tvTaskReward = view.findViewById(R.id.tv_task_reward);
        TextView tvTaskInviter = view.findViewById(R.id.tv_task_inviter);
        
        tvTaskTitle.setText(task.getTitle());
        tvTaskDesc.setText(task.getDescription());
        
        // 显示提交者
        tvTaskSubmitter.setText("提交者：" + task.getUsername());
        
        // 显示任务奖励信息
        if (tvTaskReward != null) {
            double taskReward = task.getReward();
            tvTaskReward.setText(String.format(Locale.getDefault(), "奖励金额: %.2f元", taskReward));
            tvTaskReward.setVisibility(View.VISIBLE);
            
            // 获取并显示用户推荐人信息
            if (tvTaskInviter != null) {
                String username = task.getUsername();
                
                // 通过API获取推荐人信息
                getInviterInfo(username, tvTaskInviter);
            }
        }
        
        // 加载任务图片
        if (task.getImageUrl() != null && !task.getImageUrl().isEmpty()) {
            ivTaskImage.setVisibility(View.VISIBLE);
            
            // 检查是否是网络图片还是本地图片
            if (task.getImageUrl().startsWith("http")) {
                // 网络图片，使用Picasso加载
                Picasso.get().load(task.getImageUrl()).into(ivTaskImage);
            } else {
                // 本地图片，使用ImageUtils加载
                Bitmap bitmap = ImageUtils.loadImageFromPath(task.getImageUrl());
                if (bitmap != null) {
                    ivTaskImage.setImageBitmap(bitmap);
                } else {
                    // 图片加载失败
                    ivTaskImage.setVisibility(View.GONE);
                    Toast.makeText(this, "任务图片加载失败", Toast.LENGTH_SHORT).show();
                }
            }
        } else {
            ivTaskImage.setVisibility(View.GONE);
        }
        
        AlertDialog dialog = builder.create();
        dialog.show();
        
        btnApprove.setOnClickListener(v -> {
            approveTask(task);
            dialog.dismiss();
        });
        
        btnReject.setOnClickListener(v -> {
            showRejectReasonDialog(task);
            dialog.dismiss();
        });
    }
    
    private void getInviterInfo(String username, TextView tvInviter) {
        // 设置默认值，避免空显示
        tvInviter.setText("正在加载推荐人信息...");
        tvInviter.setVisibility(View.VISIBLE);
        
        String token = NetworkUtils.getAuthToken(this);
        if (token == null || token.isEmpty()) {
            tvInviter.setText("无法获取推荐人信息: 未登录");
            return;
        }
        
        // 使用API获取用户的推荐人信息
        UserApi api = NetworkUtils.getAuthenticatedUserApi(this);
        Call<InviterResponse> call = api.getUserInviter("Bearer " + token, username);
        
        call.enqueue(new Callback<InviterResponse>() {
            @Override
            public void onResponse(Call<InviterResponse> call, Response<InviterResponse> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    InviterResponse data = response.body();
                    
                    // 格式化推荐人信息
                    StringBuilder inviterInfo = new StringBuilder("推荐人链: ");
                    
                    // 如果有直接推荐人
                    if (data.getDirectInviter() != null) {
                        inviterInfo.append(data.getDirectInviter().getUsername())
                                 .append(String.format(Locale.getDefault(), " (%.1f%%)", 
                                         data.getDirectInviter().getRewardRatio()));
                        
                        // 如果有二级推荐人
                        if (data.getLevel2Inviter() != null) {
                            inviterInfo.append(" → ")
                                     .append(data.getLevel2Inviter().getUsername())
                                     .append(String.format(Locale.getDefault(), " (%.1f%%)", 
                                             data.getLevel2Inviter().getRewardRatio()));
                            
                            // 如果有三级推荐人
                            if (data.getLevel3Inviter() != null) {
                                inviterInfo.append(" → ")
                                         .append(data.getLevel3Inviter().getUsername())
                                         .append(String.format(Locale.getDefault(), " (%.1f%%)", 
                                                 data.getLevel3Inviter().getRewardRatio()));
                            }
                        }
                        
                        tvInviter.setText(inviterInfo.toString());
                    } else {
                        tvInviter.setText("该用户无推荐人");
                    }
                } else {
                    tvInviter.setText("无法获取推荐人信息");
                }
            }
            
            @Override
            public void onFailure(Call<InviterResponse> call, Throwable t) {
                tvInviter.setText("获取推荐人信息失败: 网络错误");
            }
        });
    }
    
    private void approveTask(Task task) {
        String token = NetworkUtils.getAuthToken(this);
        if (token == null || token.isEmpty()) {
            Toast.makeText(this, "未登录，无法执行操作", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Map<String, Object> approvalData = new HashMap<>();
        approvalData.put("taskId", task.getId());
        
        UserApi api = NetworkUtils.getAuthenticatedUserApi(this);
        Call<CommonResponse> call = api.approveTask("Bearer " + token, approvalData);
        
        call.enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        Toast.makeText(TaskManagementActivity.this, "任务审核通过成功", Toast.LENGTH_SHORT).show();
                        loadTasks();
                    } else {
                        Toast.makeText(TaskManagementActivity.this, "审核失败: " + response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(TaskManagementActivity.this, "审核失败，错误码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                Toast.makeText(TaskManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                // 回退到上面定义的updateTask方法
                updateTask(task, Task.STATUS_COMPLETED);
            }
        });
    }
    
    private void showRejectReasonDialog(Task task) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_reject_reason, null);
        builder.setView(view);
        
        EditText etReason = view.findViewById(R.id.et_reject_reason);
        Button btnSubmit = view.findViewById(R.id.btn_submit_reject);
        
        AlertDialog dialog = builder.create();
        dialog.show();
        
        btnSubmit.setOnClickListener(v -> {
            String reason = etReason.getText().toString().trim();
            if (reason.isEmpty()) {
                Toast.makeText(this, "请输入拒绝原因", Toast.LENGTH_SHORT).show();
                return;
            }
            
            rejectTask(task, reason);
            dialog.dismiss();
        });
    }
    
    private void rejectTask(Task task, String reason) {
        String token = NetworkUtils.getAuthToken(this);
        if (token == null || token.isEmpty()) {
            Toast.makeText(this, "未登录，无法执行操作", Toast.LENGTH_SHORT).show();
            return;
        }
        
        Map<String, Object> rejectionData = new HashMap<>();
        rejectionData.put("taskId", task.getId());
        rejectionData.put("reason", reason);
        
        userApi.rejectTask("Bearer " + token, rejectionData).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().isSuccess()) {
                        Toast.makeText(TaskManagementActivity.this, "任务拒绝成功", Toast.LENGTH_SHORT).show();
                        loadTasks();
                    } else {
                        Toast.makeText(TaskManagementActivity.this, "拒绝失败: " + response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(TaskManagementActivity.this, "拒绝失败，错误码: " + response.code(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                Toast.makeText(TaskManagementActivity.this, "网络请求失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updateTask(Task task, int newStatus) {
        task.setStatus(newStatus);
        task.setReviewTime(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault()).format(new Date()));
        task.setContext(this); // 设置上下文
        
        // 通过API更新任务
        boolean success = NetworkUtils.updateTask(task);
        if (success) {
            String statusText = (newStatus == Task.STATUS_COMPLETED) ? "通过" : "拒绝";
            Toast.makeText(this, "任务已" + statusText, Toast.LENGTH_SHORT).show();
            loadTasks();
        } else {
            Toast.makeText(this, "操作失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }
}